package com.kh.statistics.video.core.statistics;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kh.statistics.video.constant.PlatformConstant;
import com.kh.statistics.video.core.MediaContext;
import com.kh.statistics.video.core.Platform;
import com.kh.statistics.video.core.login.entity.XiaoHongShuHealthCheckResponse;
import com.kh.statistics.video.core.script.DefualtParseExecResult;
import com.kh.statistics.video.core.script.ShellExecutor;
import com.kh.statistics.video.core.statistics.entity.XhsUserPostResp;
import com.kh.statistics.video.entity.StatisticsInfo;
import com.kh.statistics.video.entity.StatisticsMeta;
import com.kh.statistics.video.entity.StatisticsOne;
import com.kh.statistics.video.helper.ExcelHelper;
import com.kh.statistics.video.helper.StatisticsHttpHelper;
import com.kh.statistics.video.utils.ParamsUtils;
import com.kh.statistics.video.utils.SerializationUtils;
import com.kh.statistics.video.utils.SystemUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @BelongsProject: statistics
 * @BelongsPackage: com.kh.statistics.video.core.statistics
 * @Author: Hong.Kong
 * @CreateTime: 2024-05-10  09:40
 * @Description: TODO
 * @Version: 1.0
 */
@Component
@Slf4j
public class XiaoHongShuPlatform implements Platform {


    @Value("${statistics.platform.share.xhs.cmd}")
    private String cmd;

    @Value("${statistics.platform.share.xhs.postScript}")
    private String postScript;

    @Value("${statistics.platform.share.xhs.getScript}")
    private String getScript;

    @Value("${statistics.platform.share.xhs.path}")
    private String path;

    private static String shortUrlTemplate = "%s 【%s  - %s | 小红书 - 你的生活指南】 \uD83D\uDE06 %s \uD83D\uDE06 http://%s";

    @Override
    public String support() {
        return PlatformConstant.XIAO_HONG_SHU;
    }

    @Override
    public List<StatisticsInfo> getInfo(StatisticsMeta statisticsMeta) {
        return null;
    }

    @Override
    public void statistics(List<StatisticsMeta> list) {
        List<StatisticsInfo> statisticsInfoListAll = new ArrayList<>();
        for (StatisticsMeta statisticsMeta : list) {
            StatisticsInfo statisticsInfo = new StatisticsInfo();
            if ("keyMetrics".equals(statisticsMeta.getName())) {
            }
            statisticsInfoListAll.add(statisticsInfo);
        }
        ExcelHelper.export(ExcelHelper.getExcelName(list.get(0).getAccountName(), "小红书统计总"), statisticsInfoListAll, StatisticsInfo.class);
    }

    @Override
    public void oneStatistics(List<StatisticsMeta> statisticsMetaList, MediaContext mediaContext) {
        List<StatisticsOne> statisticsInfoListAll = new ArrayList<>();
        Optional<StatisticsMeta> oneStatistics = statisticsMetaList.stream().filter((item) -> null != item.getName() && "oneStatistics".equals(item.getName())).findFirst();
        if (oneStatistics.isPresent()) {
            StatisticsMeta statisticsMeta = oneStatistics.get();
            Map<String, String> headers = statisticsMeta.getHeaders();
            headers.put("X-T", String.valueOf(System.currentTimeMillis()));
            headers.put("referer", "https://creator.xiaohongshu.com/creator/notes");
            String body = StatisticsHttpHelper.request(statisticsMeta);
            log.info("小红书统计响应结果：{}", body);
            if (!handlerResponse(body)) {
                return;
            }
            List<StatisticsOne> statisticsInfos = oneDataStatistics(body, mediaContext);
//            getShortUrl(statisticsInfos, mediaContext);
            statisticsInfoListAll.addAll(statisticsInfos);
        }
        ExcelHelper.export(ExcelHelper.getExcelName(statisticsMetaList.get(0).getAccountName(), "小红书单条统计"), statisticsInfoListAll, StatisticsOne.class);
    }

    private void getShortUrl(List<StatisticsOne> list, MediaContext mediaContext) {
        ///api/sns/web/short_url
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<String> list1 = ShellExecutor.parseScript(cmd);
        DefualtParseExecResult defualtParseExecResult = new DefualtParseExecResult();
        String userId = ParamsUtils.parseCookiesAndGet(mediaContext.getVideoAccountsLogin().getCookies(), "x-user-id-creator.xiaohongshu.com");
        XhsUserPostResp.DataDTO.NotesDTO.UserDTO userPosted = getUserPosted(userId, new ArrayList<>(list1), defualtParseExecResult);
        log.info("userPosted：{}", userPosted);
        Random rand = new Random();
        list.forEach(item -> {
            List<String> codeNewList = new ArrayList<>(list1);
            String code = getCode(item, codeNewList, defualtParseExecResult);
            List<String> shortUrlList = new ArrayList<>(list1);
            String shortUrl = getShortUrl(item, shortUrlList, defualtParseExecResult);
            log.info("最后生成结果：code：{}，shortUrl：{}", code, shortUrl);
            int num = rand.nextInt(99) + 1;
            String url = String.format(shortUrlTemplate, num, item.getWorks(), userPosted.getNickName(), code, shortUrl);
            log.info("最后生成结果：{}", url);
            item.setLink(url);
        });
    }

    private String getCode(StatisticsOne statisticsOne, List<String> newList, DefualtParseExecResult defualtParseExecResult) {
        newList.add(postScript);
        newList.add("--api");
        newList.add("/api/sns/web/share/code");
        JSONObject jsonObject = new JSONObject();
        JSONObject id = new JSONObject();
        id.put("id", statisticsOne.getAwemeId());
        jsonObject.put("share_code", id);
        newList.add("--data");
        if (SystemUtil.isWindows()) {
            newList.add(JSONObject.toJSONString(jsonObject.toJSONString()));
        } else {
            newList.add(jsonObject.toJSONString());
        }
        Map<String, List<String>> retMap = ShellExecutor.execute(path, newList.toArray(new String[0]));
        String parse = defualtParseExecResult.parse(retMap, "xhs=");
        JSONObject codeObj = JSONObject.parseObject(parse);
        String codeData = codeObj.getString("data");
        log.info("code_data:{}", codeData);
        return codeData;
    }

    private XhsUserPostResp.DataDTO.NotesDTO.UserDTO getUserPosted(String userId, List<String> newList, DefualtParseExecResult defualtParseExecResult) {
        newList.add(getScript);
        Map<String, Object> map = new HashMap<>();
        map.put("num", 30);
        map.put("user_id", userId);
        map.put("image_formats", "jpg,webp,avif");
        map.put("cursor","");
        map.put("id", 1);
        String params = HttpUtil.toParams(map);
        newList.add(ShellExecutor.parseParam("/api/sns/web/v1/user_posted?" + params));
        Map<String, List<String>> retMap = ShellExecutor.execute(path, newList.toArray(new String[0]));
        String parse = defualtParseExecResult.parse(retMap, "xhs=");
        XhsUserPostResp codeObj = JSONObject.parseObject(parse, XhsUserPostResp.class);
        if (null == codeObj || !codeObj.getSuccess()) {
            throw new RuntimeException("获取小红书用户发布数据失败");
        }
        List<XhsUserPostResp.DataDTO.NotesDTO> notes = codeObj.getData().getNotes();
        if (CollectionUtils.isEmpty(notes)) {
            throw new RuntimeException("小红书用户发布数据为空");
        }

        return notes.get(0).getUser();
    }

    private String getShortUrl(StatisticsOne statisticsOne, List<String> newList, DefualtParseExecResult defualtParseExecResult) {
        newList.add(postScript);
        newList.add("--api");
        newList.add("/api/sns/web/short_url");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("original_url", statisticsOne.getLink() + "?source=webshare");
        newList.add("--data");
        if (SystemUtil.isWindows()) {
            newList.add(JSONObject.toJSONString(jsonObject.toJSONString()));
        } else {
            newList.add(jsonObject.toJSONString());
        }
        Map<String, List<String>> retMap = ShellExecutor.execute(path, newList.toArray(new String[0]));
        String parse = defualtParseExecResult.parse(retMap, "xhs=");
        JSONObject codeObj = JSONObject.parseObject(parse);
        JSONObject shortUrlData = codeObj.getJSONObject("data");

        log.info("shortUrlData:{}", shortUrlData);
        return shortUrlData.getString("short_url");
    }

    @Override
    public boolean handlerResponse(String body) {
        XiaoHongShuHealthCheckResponse response = SerializationUtils.deserialize(body, XiaoHongShuHealthCheckResponse.class);
        return null != response && response.getResult() == 0 && null != response.getData();
    }

    private List<StatisticsOne> oneDataStatistics(String body, MediaContext mediaContext) {
        List<StatisticsOne> itemList = new ArrayList<>();
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONObject dataObject = jsonObject.getJSONObject("data");
        JSONArray noteInfos = dataObject.getJSONArray("note_infos");
        for (Object o : noteInfos) {
            StatisticsOne statisticsOne = new StatisticsOne();
            JSONObject item = (JSONObject) o;
            String title = item.getString("title");
            statisticsOne.setWorks(title);
            String id = item.getString("id");
            statisticsOne.setLink("https://www.xiaohongshu.com/explore/" + id);
            statisticsOne.setAwemeId(id);
            Long post_time = item.getLong("post_time");
            statisticsOne.setPushDate(DateUtil.format(new Date(post_time), "yyyy/MM/dd HH:mm:ss"));
            Long read = item.getLong("read");
            statisticsOne.setExposure(read);
            //TODO 完播率
            Long like = item.getLong("like");
            statisticsOne.setClicksNumber(like);
            Long commentCount = item.getLong("comment");
            statisticsOne.setCommentsNumber(commentCount);
            itemList.add(statisticsOne);
        }
        return itemList;
    }
}
